//和用户相关的状态管理
import { createSlice } from "@reduxjs/toolkit"
import { loginApi,getProfileApi } from "@/apis/user"
import { setToken as _setToken, getToken ,removeToken} from "@/utils"
const userStore = createSlice({
    name: "user",
    //数据状态
    initialState: {
        token: getToken(),
        userInfo: {},
    },
    //动作,同步修改方法
    reducers: {
        setToken(state, action) {
            state.token = action.payload
            //localStorage存一份
            // localStorage.setItem("token_key", action.payload)
            _setToken(action.payload)
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        cleanUserInfo(state) {
           state.token=""
           state.userInfo={}
           removeToken()
        }
    }
})
//解构出ActionCreate

const { setToken, setUserInfo,cleanUserInfo } = userStore.actions
//获取reducer函数

const userReducer = userStore.reducer
const fetchLogin = (loginFrom) => {
    return async (dispatch) => {
        //发生异步请求
        const res = await loginApi(loginFrom)
        //提交同步action 进行token的存入
        const token = res.data.token
        console.log("token----------->" + token)
        dispatch(setToken(token))
    }
}
const fetchUserInfo = () => {
    return async (dispatch) => {
        //发生异步请求
        const res = await getProfileApi()
        dispatch(setUserInfo(res.data))
        //提交同步action 进行token的存入

    }
}
export { setToken, fetchLogin, fetchUserInfo,cleanUserInfo }

export default userReducer